package com.eh.reflectoin;

import com.eh.reflectoin.dto.MethodInvokerRequest;
import com.eh.reflectoin.exception.InvokeMethodException;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by David on 2016/4/29.
 */
public class MethodInvokerUtil {
    public static Object invoke(MethodInvokerRequest methodInvokerRequest) {
        try {
            Object bean = methodInvokerRequest.getBean();
            String methodName = methodInvokerRequest.getMethodName();
            Object[] args = methodInvokerRequest.getArgs();
            Method method = bean.getClass().getMethod(methodName, getMethodClasses(args));
            return method.invoke(bean, args);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        throw new InvokeMethodException(
                String.format("方法[%s]调用异常！", methodInvokerRequest.getMethodName()));
    }

    private static Class[] getMethodClasses(Object... args) {
        if (args == null || args.length == 0) {
            return null;
        }
        Class[] results = new Class[args.length];
        for (int i = 0; i < args.length; i++) {
            results[i] = args[i].getClass();
        }
        return results;
    }
}
